import base64
import logging

import requests
import json

from bs4 import BeautifulSoup

from wu.seal.emailtool.EmailTemplate import Item


class Utils:
    __logger = logging.getLogger('Utils')
    __apk_link_template = """http://10.88.0.23/{app_name_lower_case}_{branch_name}/pn1/{app_version}/index.html"""
    __iteration_item_story_link_template = """https://www.tapd.cn/33700533/prong/stories/view/{story_id}"""
    __iteration_item_bug_link_template = """https://www.tapd.cn/33700533/bugtrace/bugs/view?bug_id={story_id}"""
    __iteration_bug_list_link_template = """https://m.tapd.cn/33700533/nwx/iteration/cgi_list_workitems/{iteration_id}/bug"""

    def getAppName(self, branch_name: str):
        if "dingtone" in branch_name.lower():
            return "Dingtone"
        elif "telos" in branch_name.lower():
            return "Telos"
        else:
            return "TalkU"

    def getAppVersion(self, branch_name: str):
        if branch_name.__contains__("_patch"):
            endIndex = branch_name.rindex('_patch')
            branch_name = branch_name[:endIndex]
        return branch_name[branch_name.index("_") + 1:].replace("_", ".")

    def getAPKLink(self, branch_name: str):
        return self.__apk_link_template.replace("{app_name_lower_case}", self.getAppName(branch_name).lower()).replace(
            "{branch_name}", branch_name.lower()).replace("{app_version}", self.getAppVersion(branch_name))

    def getTapdLink(selfs, branch_name: str):
        app_name = selfs.getAppName(branch_name)
        app_version = selfs.getAppVersion(branch_name)
        __tapd_iteration_link_template = "https://www.tapd.cn/33700533/prong/iterations/view/{iteration_id}"

        loginUrl = 'https://m.tapd.cn/nwx/auth/cgi_do_auth?react=1&time=1545366881875'

        param = {"account": "seal.wu@dingtone.me",
                 "pwd": "ISpfILnU4azzeVaErDdywA==",
                 "encrypt_key": "uq/7SrX9Bn82c1XKR2pOx4QABiy+xJ2qfu5ev9m+EtI=",
                 "encrypt_iv": "SgaHAQNdgog7Fo18Pd6lWA==",
                 "img_code": ""}
        req = requests.post(url=loginUrl, data=param)
        cookies = req.cookies
        selfs.__logger.info(req.text)

        params = {"react": 1, "time": "1545367935473", "page": 1}
        req = requests.get('https://m.tapd.cn/33700533/nwx/iteration/cgi_list_data', params=params, cookies=cookies)
        __json = json.loads(req.text)
        selfs.__logger.info("抓取到的版本迭代列表为：%s" % __json)
        iteration_id: str = None
        for each in __json['data']['data_list']:
            iteration_name: str = each['base']['name']
            if "android" in iteration_name.lower() and app_version.lower() in iteration_name.lower() and app_name.lower() in iteration_name.lower():
                iteration_id = each['base']["id"]
                break

        if iteration_id is None:
            selfs.__logger.error("没有获取到TAPD上的版本迭代信息，请确认TAPD上有建相应的版本迭代")
        tapd_iteration_link = __tapd_iteration_link_template.replace('{iteration_id}', iteration_id)
        return tapd_iteration_link

    def get_reversion(self, branch_name: str):
        req = requests.get(self.getAPKLink(branch_name))
        bfs = BeautifulSoup(req.text, "html.parser")
        detail_version_info: str = bfs.find('td', class_="instructions_app").string
        return detail_version_info[detail_version_info.rindex(".") + 1:]

    def get_app_version_code(self, branch_name: str):
        app_name = self.getAppName(branch_name)
        git_lab_access_token = """U4E2RNTg5Aobk3NUUs-K"""
        if app_name.lower() == "telos":
            get_file_url = """http://10.88.0.31/api/v3/projects/4/repository/files?private_token=%s&file_path=DingtoneAndroid/build.gradle&ref=%s""" % (
                git_lab_access_token, branch_name)
            responseContentText = requests.get(get_file_url).text
            loadedJSON = json.loads(responseContentText)
            self.__logger.info(f"从gitlab 读取到的内容是{responseContentText},加载后的JSON 是{loadedJSON}")
            __content: str = str(base64.b64decode(loadedJSON['content']))
            self.__logger.info(f"最后取得的build.gradle文件的内容是{__content}")
            left = __content.index("{")
            right = __content.index("}")
            app_info = __content[left + 1:right].replace(r"\n", "\n").strip()
            app_version_code_line = app_info.split("\n")[1]
            app_version_code = app_version_code_line.split("=")[1].strip()
            return app_version_code
        else:
            get_file_url = """http://10.88.0.31/api/v3/projects/4/repository/files?private_token=%s&file_path=DingtoneAndroid/config.gradle&ref=%s""" % (
                git_lab_access_token, branch_name)
            __content: str = str(base64.b64decode(json.loads(requests.get(get_file_url).text)['content']))
            left = __content.index("talku")
            right = __content.rindex(r"}")
            content = __content[left:right].replace(r"\n", "")
            configs = content.split("] ")
            for each in configs:
                if app_name.lower() in each.lower():
                    return each[each.index(":") + 1:each.index(",")].strip()

    def get_iteration_story_items(self, branch_name: str):
        app_name = self.getAppName(branch_name)
        app_version = self.getAppVersion(branch_name)
        __tapd_iteration_detail_link_template = "https://m.tapd.cn/33700533/nwx/iteration/cgi_list_workitems/{iteration_id}/story"

        loginUrl = 'https://m.tapd.cn/nwx/auth/cgi_do_auth?react=1&time=1545366881875'

        param = {"account": "seal.wu@dingtone.me",
                 "pwd": "ISpfILnU4azzeVaErDdywA==",
                 "encrypt_key": "uq/7SrX9Bn82c1XKR2pOx4QABiy+xJ2qfu5ev9m+EtI=",
                 "encrypt_iv": "SgaHAQNdgog7Fo18Pd6lWA==",
                 "img_code": ""}
        req = requests.post(url=loginUrl, data=param)
        cookies = req.cookies
        self.__logger.info(req.text)

        params = {"react": 1, "time": "1545367935473", "page": 1}
        req = requests.get('https://m.tapd.cn/33700533/nwx/iteration/cgi_list_data', params=params, cookies=cookies)
        __json = json.loads(req.text)
        self.__logger.info("抓取到的版本迭代列表为：%s" % __json)
        iteration_id: str
        for each in __json['data']['data_list']:
            iteration_name: str = each['base']['name']
            if app_version.lower() in iteration_name.lower() and app_name.lower() in iteration_name.lower():
                iteration_id = each['base']["id"]
                break
        self.__logger.info("抓取到的版本迭代id为：%s" % iteration_id)
        iteration_detail_link = __tapd_iteration_detail_link_template.replace('{iteration_id}', iteration_id)
        items = list()
        page = 0
        __json = None
        while __json is None or __json['data']['total_count'] > items.__len__():
            page += 1
            self.__logger.info(f"current param page is {page}")
            __json = self.__get_iteration_story_item_list(__json, cookies, items, iteration_detail_link, page)

        return items

    def get_iteration_bug_items(self, branch_name: str):
        app_name = self.getAppName(branch_name)
        app_version = self.getAppVersion(branch_name)
        __tapd_iteration_detail_link_template = "https://m.tapd.cn/33700533/nwx/iteration/cgi_list_workitems/{iteration_id}/story"

        loginUrl = 'https://m.tapd.cn/nwx/auth/cgi_do_auth?react=1&time=1545366881875'

        param = {"account": "seal.wu@dingtone.me",
                 "pwd": "ISpfILnU4azzeVaErDdywA==",
                 "encrypt_key": "uq/7SrX9Bn82c1XKR2pOx4QABiy+xJ2qfu5ev9m+EtI=",
                 "encrypt_iv": "SgaHAQNdgog7Fo18Pd6lWA==",
                 "img_code": ""}
        req = requests.post(url=loginUrl, data=param)
        cookies = req.cookies
        self.__logger.info(req.text)

        params = {"react": 1, "time": "1545367935473", "page": 1}
        req = requests.get('https://m.tapd.cn/33700533/nwx/iteration/cgi_list_data', params=params, cookies=cookies)
        __json = json.loads(req.text)
        self.__logger.info("抓取到的版本迭代列表为：%s" % __json)
        iteration_id: str
        for each in __json['data']['data_list']:
            iteration_name: str = each['base']['name']
            if app_version.lower() in iteration_name.lower() and app_name.lower() in iteration_name.lower():
                iteration_id = each['base']["id"]
                break
        self.__logger.info("抓取到的版本迭代id为：%s" % iteration_id)
        iteration_bugs_link = self.__iteration_bug_list_link_template.replace('{iteration_id}', iteration_id)
        items = list()
        page = 0
        __json = None
        while __json is None or __json['data']['total_count'] > items.__len__():
            page += 1
            self.__logger.info(f"current param page is {page}")
            __json = self.__get_iteration_bug_item_list(__json, cookies, items, iteration_bugs_link, page)

        return items

    def __get_iteration_story_item_list(self, __json, cookies, items, iteration_detail_link, page):
        params = {"react": 1, "time": "1545367935473", "page": page, 'limit': 30}
        self.__logger.info(f"抓取到的迭代详情界面链接为{iteration_detail_link}")
        req = requests.get(iteration_detail_link, params=params, cookies=cookies)
        __json = json.loads(req.text)
        self.__logger.info(f"抓取到的迭代需求列表为{__json}")
        for item in __json['data']['data_list']:
            item_name = item['name']
            item_link = self.__iteration_item_story_link_template.replace('{story_id}', item['id'])
            items.append(Item(item_name, item_link))
        return __json

    def __get_iteration_bug_item_list(self, __json, cookies, items, iteration_detail_link, page):
        params = {"react": 1, "time": "1545367935473", "page": page, 'limit': 30}
        self.__logger.info(f"抓取到的迭代详情界面链接为{iteration_detail_link}")
        req = requests.get(iteration_detail_link, params=params, cookies=cookies)
        __json = json.loads(req.text)
        self.__logger.info(f"抓取到的迭代缺陷列表为{__json}")
        for item in __json['data']['data_list']:
            item_name = item['name']
            item_link = self.__iteration_item_bug_link_template.replace('{story_id}', item['id'])
            items.append(Item(item_name, item_link))
        return __json


if __name__ == '__main__':
    logging.basicConfig(level=logging.INFO)
    code = Utils().get_app_version_code("Telos_2_0_0")
    print(code)
